package com.longrise.co.ui.mine.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.co.R;
import com.longrise.co.api.CommonPara;
import com.longrise.co.ui.carfiles.widget.AddPhotoDialog;
import com.longrise.co.ui.login.fragment.LoginFragment;
import com.longrise.co.ui.mine.contract.MineContract;
import com.longrise.co.ui.mine.model.MineModel;
import com.longrise.co.ui.mine.model.RxModifyBackData;
import com.longrise.co.ui.mine.model.UserInfo;
import com.longrise.co.ui.mine.presenter.MinePresenter;
import com.longrise.co.utils.Constants;
import com.ly.common.base.BaseFragment;
import com.ly.common.baserx.RxBus;
import com.ly.common.commonutils.ImageLoaderUtils;
import com.ly.common.commonutils.StringUtils;
import com.ly.common.dialog.DialogOnClickListener;
import com.ly.common.dialog.MDAlertDialog;

import java.io.File;

import butterknife.Bind;
import butterknife.OnClick;
import rx.functions.Action1;

import static com.longrise.co.R.id.car_num;
import static com.longrise.co.R.id.mine_info;
import static com.longrise.co.ui.mine.fragment.MyProfileFragment.RX_MODIFY_MOBILE;
import static com.longrise.co.ui.mine.fragment.MyProfileFragment.RX_MODIFY_NICK;
import static com.longrise.co.ui.mine.fragment.MyProfileFragment.RX_REAL_NAME;

/**
 * Created by luoyang on 2017-6-26.
 */

public class MineFragment extends BaseFragment<MinePresenter, MineModel> implements MineContract.MineView<UserInfo>, SwipeRefreshLayout.OnRefreshListener, DialogOnClickListener, AddPhotoDialog.OnSelectPhotoListener, TakePhoto.TakeResultListener, InvokeListener {

    @Bind(R.id.photo)
    ImageView photo;
    @Bind(R.id.name)
    TextView name;
    @Bind(R.id.car_info)
    TextView carInfo;
    @Bind(R.id.message)
    TextView message;
    @Bind(R.id.evaluation)
    TextView evaluation;
    @Bind(R.id.complaint)
    TextView complaint;
    @Bind(car_num)
    TextView carNum;
    @Bind(R.id.swipe_refresh)
    SwipeRefreshLayout swipeRefresh;
    @Bind(mine_info)
    RelativeLayout mineInfoRl;
    @Bind(R.id.mine_login)
    RelativeLayout mineLoginRl;
    @Bind(R.id.kckp_rl)
    RelativeLayout kckpRl;
    @Bind(R.id.exit_login)
    Button exitLogin;

    private UserInfo mUserInfo;

    private boolean isFirstLoad = true;

    private MDAlertDialog mDialog;

    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private Uri imageUri;
    private TImage mCurrentImage;

    private AddPhotoDialog mAddPhotoDialog;

    @Override
    protected int getLayoutResource() {
        return R.layout.fg_mine;
    }

    @Override
    public void initPresenter() {
       mPresenter.setVM(this, mModel);
    }

    @Override
    protected void initView() {
        swipeRefresh.setOnRefreshListener(this);
        swipeRefresh.setColorSchemeColors(Constants.RECYCLER_RGB);
        initPhotoSelect();
        mRxManager.on(Constants.RX_EVENT_MODIFY_NICK, new Action1<RxModifyBackData>() {
            @Override
            public void call(RxModifyBackData s) {
                switch (s.type) {
                    case RX_MODIFY_NICK:
                        setText(name, s.value);
                        mUserInfo.setNickname(s.value);
                        break;
                    case RX_MODIFY_MOBILE:
                        break;
                    case RX_REAL_NAME:
                        break;
                }

            }
        });

        mRxManager.on(Constants.RX_EVENT_REFRESH_MINE, new Action1<String>() {
            @Override
            public void call(String s) {
                if(checkLogin() && "loginSuccess".equals(s)) {
                    mPresenter.getUserInfo(true);
                    return ;
                }
                isFirstLoad = true;
            }
        });

        boolean isShowKckp = CommonPara.getInstance().isShowKckpSet();
        kckpRl.setVisibility(isShowKckp ? View.VISIBLE : View.GONE);

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser && isFirstLoad) {
            Log.i("MineFragment", "coming MineFragment....");
            isFirstLoad = false;
            if(checkLogin()) {
                mPresenter.getUserInfo(true);
            }
        }
    }

    public static MineFragment newInstance() {
        return new MineFragment();
    }

    @Override
    public void requestSuccess(UserInfo userInfo) {
        if(userInfo == null) {
            return ;
        }
        mUserInfo = userInfo;

        if(!StringUtils.isEmpty(userInfo.getAuthstatus())) {
           CommonPara.getInstance().setAuthStatus(!"未认证".equals(userInfo.getAuthstatus()));
        }

        if(photo != null && !StringUtils.isEmpty(userInfo.getPhoto())) {
            ImageLoaderUtils.displayCircle(getContext(), photo, userInfo.getPhoto());
        }else{
            photo.setImageResource(R.drawable.test_photo);
        }

        if(carInfo != null && !StringUtils.isEmpty(userInfo.getCarnum())) {
            SpannableString styledText = new SpannableString("您当前已绑定 " + userInfo.getCarnum() + " 辆车辆");
            styledText.setSpan(new TextAppearanceSpan(getContext(), R.style.mineWhite), 0, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            styledText.setSpan(new TextAppearanceSpan(getContext(), R.style.mineRed), 7, 7 + userInfo.getCarnum().length() , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            styledText.setSpan(new TextAppearanceSpan(getContext(), R.style.mineWhite), 7 + userInfo.getCarnum().length(), 11 + userInfo.getCarnum().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            carInfo.setText(styledText, TextView.BufferType.SPANNABLE);
            carNum.setText(userInfo.getCarnum());
        }

        if(name != null && !StringUtils.isEmpty(userInfo.getNickname())) {
            name.setText(userInfo.getNickname());
        }else {
            name.setText("");
        }

        if(complaint != null ) {
            complaint.setText(String.valueOf(userInfo.getComplainnum()));
        }

        if(evaluation != null ) {
            evaluation.setText(String.valueOf(userInfo.getEvaluatenum()));
        }

    }

    @Override
    public void onRequestComplete() {
        if(swipeRefresh.isRefreshing()) {
            swipeRefresh.setRefreshing(false);
        }
    }

    private void initDialog() {
        mDialog = new MDAlertDialog.Builder(getContext())
                .setContentText("确定退出登录？")
                .setOnclickListener(this)
                .build();
    }


    @OnClick({R.id.car_rl, R.id.share_rl, R.id.collect_rl, R.id.user_feedback_rl, R.id.about_rl, R.id.exit_login, R.id.my_profile, R.id.my_complaint_rl, R.id.my_evaluation_rl, R.id.photo, R.id.message_rl, R.id.mine_login, R.id.kckp_rl})
    public void onViewClicked(View view) {
        if (checkDoubleClick()) {
            switch (view.getId()) {
                case R.id.my_profile:
                    if(!CommonPara.getInstance().isLogin()) {
                        mRxManager.post(Constants.RX_EVENT_NEXT_PAGE, LoginFragment.newInstance());
                        return ;
                    }
                    //我的资料
                    if(mUserInfo == null) {
                        return;
                    }
                    MyProfileFragment profileFragment = MyProfileFragment.newInstance(mUserInfo);
                    profileFragment.setOnSuccessListener(new MyProfileFragment.OnSuccessListener() {
                        @Override
                        public void onSuccess() {
                            mPresenter.getUserInfo(true);
                        }
                    });
                    RxBus.getInstance().post(Constants.RX_EVENT_NEXT_PAGE, profileFragment);
                    break;
                case R.id.car_rl:
                    if(!CommonPara.getInstance().isLogin()) {
                        mRxManager.post(Constants.RX_EVENT_NEXT_PAGE, LoginFragment.newInstance());
                        return ;
                    }
                    MyCarFragment myCarFragment = MyCarFragment.newInstance();
                    myCarFragment.setOnSuccessListener(new MyCarFragment.OnSuccessListener() {
                        @Override
                        public void onSuccess() {
                            mPresenter.getUserInfo(true);
                        }
                    });
                    mRxManager.post(Constants.RX_EVENT_NEXT_PAGE, myCarFragment);
                    break;
                case R.id.share_rl:
                    mRxManager.post(Constants.RX_EVENT_NEXT_PAGE, ShareFragment.newInstance());
                    break;
                case R.id.collect_rl:
                    break;
                case R.id.user_feedback_rl:
                    mRxManager.post(Constants.RX_EVENT_NEXT_PAGE, UserFeedBackFragment.newInstance());
                    break;
                case R.id.about_rl:
                    mRxManager.post(Constants.RX_EVENT_NEXT_PAGE, AboutFragment.newInstance());
                    break;
                case R.id.my_complaint_rl:
                    if(!CommonPara.getInstance().isLogin()) {
                        mRxManager.post(Constants.RX_EVENT_NEXT_PAGE, LoginFragment.newInstance());
                        return ;
                    }
                    mRxManager.post(Constants.RX_EVENT_NEXT_PAGE, MineComplaintFragment.newInstance());
                    break;
                case R.id.my_evaluation_rl:
                    if(!CommonPara.getInstance().isLogin()) {
                        mRxManager.post(Constants.RX_EVENT_NEXT_PAGE, LoginFragment.newInstance());
                        return ;
                    }
                    mRxManager.post(Constants.RX_EVENT_NEXT_PAGE, MineEvaluationFragment.newInstance());
                    break;
                case R.id.photo:
                    //上传照片
                    if(mAddPhotoDialog == null) {
                        initAddPhotoDialog();
                    }
                  mAddPhotoDialog.show();
                    break;
                case R.id.exit_login:
                   if(mDialog == null) {
                        initDialog();
                   }
                   mDialog.show();
                    break;
                case R.id.message_rl :
                    if(!CommonPara.getInstance().isLogin()) {
                        mRxManager.post(Constants.RX_EVENT_NEXT_PAGE, LoginFragment.newInstance());
                        return ;
                    }
                    mRxManager.post(Constants.RX_EVENT_NEXT_PAGE, MessageListFragment.newInstance());
                    break;
                case R.id.mine_login :
                    mRxManager.post(Constants.RX_EVENT_NEXT_PAGE, LoginFragment.newInstance());
                    break;
                case R.id.kckp_rl:
                    //kckp地址设置
                    mRxManager.post(Constants.RX_EVENT_NEXT_PAGE, KckpSetFragment.newInstance());
                    break;
            }
        }
    }

    @Override
    public void onRefresh() {
        if(checkLogin()) {
            mPresenter.getUserInfo(false);
        } else {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    swipeRefresh.setRefreshing(false);
                }
            }, 2000);
        }
    }

    @Override
    public void clickLeftButton(View view) {
        if(mDialog != null) {
            mDialog.dismiss();
        }
    }

    private boolean checkLogin() {
        boolean isLogin = CommonPara.getInstance().isLogin();
        mineInfoRl.setVisibility(isLogin ? View.VISIBLE : View.GONE);
        mineLoginRl.setVisibility(isLogin ? View.GONE : View.VISIBLE);
        exitLogin.setVisibility(isLogin ? View.VISIBLE : View.GONE);
        return isLogin;
    }

    @Override
    public void clickRightButton(View view) {
        //清理数据
        CommonPara.getInstance().clear();
        checkLogin();
        if(message!=null){
            message.setText("0");
        }
        if (evaluation!=null){
            evaluation.setText("0");
        }
        if (complaint!=null){
            complaint.setText("0");
        }
        if (carNum!=null){
            carNum.setText("0");
        }
        mRxManager.post(Constants.RX_EVENT_REFRESH_CAR_FILE, null);
        mRxManager.post(Constants.RX_EVENT_REFRESH_HOME, null);
        mRxManager.post(Constants.RX_EVENT_QXDA, 0);
        if(mDialog != null) {
            mDialog.dismiss();
        }

    }

    private void initPhotoSelect() {
        File file=new File(Environment.getExternalStorageDirectory(), "/temp/"+System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists())file.getParentFile().mkdirs();
        imageUri = Uri.fromFile(file);
        configTakePhotoOption();
    }

    private void configTakePhotoOption(){
        TakePhotoOptions.Builder builder=new TakePhotoOptions.Builder();
        builder.setWithOwnGallery(true);
        builder.setCorrectImage(false);
        takePhoto.setTakePhotoOptions(builder.create());

    }

    private void initAddPhotoDialog() {
        mAddPhotoDialog = new AddPhotoDialog(getContext(), R.style.dialog_style);
        mAddPhotoDialog.setCanceledOnTouchOutside(true);
        mAddPhotoDialog.setOnSelectPhotoListener(this);
//        mAddPhotoDialog.create();
    }

    @Override
    public void takeSuccess(TResult result) {
        try {
            if(result != null && result.getImage() != null) {
                mCurrentImage = result.getImage();
                String imageInfo = com.longrise.co.utils.StringUtils.File2Base64(result.getImage().getOriginalPath());
                EntityBean bean = new EntityBean();
                bean.set("userflag", CommonPara.getInstance().getUserFlag());
                bean.set("userimg", imageInfo);
                bean.set("user", CommonPara.getInstance().getUser());
                bean.set("sign", CommonPara.getInstance().getEnUserFlag());
                mPresenter.modifyUserInfo(bean);
//              ImageLoaderUtils.display(getContext(), drivingLicense, mCurrentImage.getOriginalPath());
//              mPresenter.uploadPhoto(imageInfo, "5");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void takeFail(TResult result, String msg) {
        showErrorTip(msg);
    }

    @Override
    public void takeCancel() {

    }

    /**
     *  获取TakePhoto实例
     * @return
     */
    public TakePhoto getTakePhoto(){
        if (takePhoto==null){
            takePhoto= (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this,this));
        }
        return takePhoto;
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type=PermissionManager.checkPermission(TContextWrap.of(this),invokeParam.getMethod());
        if(PermissionManager.TPermissionType.WAIT.equals(type)){
            this.invokeParam=invokeParam;
        }
            return type;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type=PermissionManager.onRequestPermissionsResult(requestCode,permissions,grantResults);
        PermissionManager.handlePermissionsResult(getActivity(),type,invokeParam, this);
    }

    @Override
    public void onSelect(int type) {
        switch (type) {
            case AddPhotoDialog.SELECT_ALBUM :
                //选择相册
                takePhoto.onPickFromGallery();
//                        onPickMultiple(MAX_UPLOAD_IMAGE + 1 - mAdapter.getData().size());
                break;
            case AddPhotoDialog.SELECT_PHOTO :
                //拍照
                takePhoto.onPickFromCapture(imageUri);
                break;
            case AddPhotoDialog.SELECT_CANCEL :
                break;
        }
        mAddPhotoDialog.dismiss();
    }

    @Override
    public void modifySuccess() {
        showLongToast("修改头像成功");
        onRefresh();
    }
}
